package com.zlyx.easy.log.aspect.abstracts;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.zlyx.easy.core.tool.EasyBuffer;
import com.zlyx.easy.core.tool.Ops;
import com.zlyx.easy.core.utils.DateUtils;
import com.zlyx.easy.core.utils.LogUtils;
import com.zlyx.easy.core.utils.MethodUtils;
import com.zlyx.easy.core.utils.ObjectUtils;
import com.zlyx.easy.core.utils.ThreadUtils;
import com.zlyx.easy.log.config.LogProperties;
import com.zlyx.easy.log.process.AspectProcess;

public class AbstractLogAspect {

	@Autowired(required = false)
	protected AspectProcess aspectProcess;

	@Autowired
	protected LogProperties properties;

	/**
	 * 打印参数日志
	 * 
	 * @param pjp
	 * @param realClass
	 * @param realMethod
	 * @param url
	 * @param todos
	 * @return
	 * @throws Throwable
	 */
	protected Object doPrint(ProceedingJoinPoint pjp, Class<?> realClass, Method realMethod, String url, String[] todos)
			throws Throwable {
		Object[] args = pjp.getArgs();
		if (ObjectUtils.isEmpty(todos)) {
			todos = new String[] { realClass.getName(), realMethod.getName() };
		}
		String description = Ops.toString(todos);
		LogUtils.info(realClass, EasyBuffer.newBuffer("【", ThreadUtils.getCurrentThreadCode(), "】")
				.append("\n=========================请求开始处理=========================", "\n")
				.append("开始时间 =>  ", DateUtils.getNowMs(), "\n").append("请求描述 =>  ", description, "\n")
				.append("请求路径 =>  ", url, "\n")
				.append("请求方法 =>  ", realClass.getName(), ".", realMethod.getName(), "\n")
				.append("请求参数 =>  ", MethodUtils.getParamsMap(realMethod, args), "\n").append("请求执行 =>  ", "\n"));
		Object res = doProcess(pjp, realClass, realMethod);
		LogUtils.info(realClass, EasyBuffer.newBuffer("【", ThreadUtils.getCurrentThreadCode(), "】")
				.append("\n请求结果 =>  ", JSON.toJSONString(res), "\n").append("结束时间 =>  ", DateUtils.getNowMs(), "\n")
				.append("=========================请求结束处理=========================\n"));
		return res;
	}

	/**
	 * 调用自定义切面过程
	 * 
	 * @param pjp
	 * @return
	 * @throws Throwable
	 */
	protected Object doProcess(ProceedingJoinPoint pjp, Class<?> realClass, Method realMethod) throws Throwable {
		if (aspectProcess != null) {
			return aspectProcess.doAround(pjp, realClass, realMethod);
		}
		return pjp.proceed();
	}
}
